package com.yzyz.management.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.yzyz.management.bean.AdminBean;
import com.yzyz.management.service.AdminService;
import com.yzyz.utils.CommonHandle;
import com.yzyz.utils.Global;
import com.yzyz.utils.ValidateUtils;

public class LoginController extends AbstractController {
	Log logger = LogFactory.getLog(LoginController.class);
	
	private AdminService adminService;
	
	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int failedTimes 	= 0;
		if(request.getSession().getAttribute(Global.FAILEDTIMES) != null){
			failedTimes = Integer.valueOf((Integer)request.getSession().getAttribute(Global.FAILEDTIMES));
		}
		String name 	= request.getParameter("name");
		String password = request.getParameter("password");
		if(ValidateUtils.isNull(name) || ValidateUtils.isNull(password)) {
			failedTimes ++ ;
			request.getSession().setAttribute(Global.FAILEDTIMES, failedTimes);
			ModelAndView mv = new ModelAndView("/Admin/Login/login.jsp");
			return mv;
		}
		AdminBean admin = this.adminService.login(password, name);
		if(admin == null) {
			failedTimes ++ ;
			request.getSession().setAttribute(Global.FAILEDTIMES, failedTimes);
			if(failedTimes >= 3) {
				logger.warn( request.getRemoteAddr() +" "+ CommonHandle.now() + " A hacker is trying to login with name: " + name + " password: " + password);
				ModelAndView mv = new ModelAndView("/Admin/Error/error.jsp");
				return mv;
			}
		}
		request.getSession().setAttribute(Global.ROLE, admin);
		ModelAndView mv = new ModelAndView("/management/initializer.htm");
		return mv;
	}

}
